package manager {
	import Classes.pi_events;
	
	import SEApp.se_manager;
	
	import UIFree.ObjectEvent;
	
	import api_servers.pi_myserver;
	import api_servers.pi_servers;
	
	import cardsbody.pi_pngcard;
	
	import dialogs.pi_alert;
	import dialogs.pi_effectDialog;
	import dialogs.timeAlerts.pi_alertBaseTime;
	
	import editor.pi_cardbody;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.utils.ByteArray;
	
	public class pi_manager extends se_manager {
		protected var app					: photo_inject;
//		private var _photoFromCard			: CLoader;
		private var _lastCollectFileTime	: uint;
		private var _effectDialog			: pi_effectDialog;
		private var _paidEffects			: Boolean;
		
		public function pi_manager(a_app: photo_inject) {
			super(a_app);
			_paidEffects = false;
			app = a_app;
			app.addEventListener(GDataEvent.RESPONSE, doGDResponse);
			app.addEventListener(pi_events.INBOXRELEASE, doInBox);
			app.addEventListener(pi_events.OUTBOXRELEASE, doOutBox);
			app.addEventListener(pi_events.CARDSELECT, doCardSelect);
			app.addEventListener(pi_events.URLNOTFOUND, doIOError);
			app.addEventListener(GDataEvent.IMAGELOADERROR, doIOError);
			app.addEventListener(pi_events.STARTPAYMENT, doStartPayment);
			app.addEventListener(pi_events.CLEARPRICE, doClearPrice);
			app.addEventListener(pi_events.COLLECTFILERELEASE, doCollectorResultImage);
			app.addEventListener(GDataEvent.ERRORDATARESPONSE, doErrorDataResponse);
			app.addEventListener(pi_events.PAYCARDRELEASE, doPayCard);
			app.addEventListener(pi_events.SHOWEFFECTDIALOG, showEffectDialog);
//			app.addEventListener(pi_events.PAIDEFFECTS, doPaidEffects);
			app.addEventListener(pi_events.CHANGEEFFECT, doChangeEffect);
//			app.addEventListener(pi_events.LINKRELEASE, doLinkRelease);
			app.addEventListener(pi_events.DELETECARD, doDeleteCard);
			app.addEventListener(pi_events.INVITEDIALOG, doInviteDialog);
			
			app.addEventListener(pi_events.USERALBUMS, doUserAlbum);
			
			_effectDialog = new pi_effectDialog(app.layers[3], 490, 180, 'window', false);
			_effectDialog.title.text = pi_data.EFFECTTITLE;
		}
		
/*		public function doPaidEffects(e: Event): void {
			_paidEffects = true;
		}*/
		
		protected function doUserAlbum(e: ObjectEvent): void {
			app.loadAlbums(e.object.uid);
		}
		
		protected function doChangeEffect(e: ObjectEvent): void {
			if (app.editor.cardBody is pi_pngcard) 
				(app.editor.cardBody as pi_pngcard).initEffect(e.integer);
		};
		
		protected function doInviteDialog(e: Event): void {
		}
		
		public function showEffectDialog(e: Event): void {
			_effectDialog.show();
		}
		
		public function get effectDialog(): pi_effectDialog {
			return _effectDialog;
		}
		
		protected function doDeleteCard(e: ObjectEvent): void {
			app.alert(pi_data.WARNING, pi_data.DELETECARDIS, function(): void {
				app.myserver.deleteCard(e.object.send_id, function(data: Object): void {
					app.dispatchEvent(new ObjectEvent(pi_events.CARDREMOVED, e.object));
				});
			}, true);
		}
		
		protected function doErrorDataResponse(e: GDataEvent): void {
			app.alert(pi_data.ERROR, pi_data.SERVERNOACCESS + '\n' + e.data);
		}
		
		protected function doIOError(e: GDataEvent): void {
			var p: Array = e.data.split(':');
			if (p.length > 1) {
				p = p[0].split('#');
				if (p.length > 1) {
					switch (p[1]) {
						case '2036':  app.alert(pi_data.ERROR, Utils.sprintf(pi_data.PHOTONOTACCESS, e.data));
										return;
					}
				}
			}
			app.alert(pi_data.ERROR, e.data);
		}
		
		public function doClearPrice(e: ObjectEvent): void {
			var cardsId: Array = e.object as Array;
			for (var i:int = 0; i<pi_data.maskInfoList.length; i++) {
				if (pi_data.maskInfoList[i].price && 
					(cardsId.indexOf(pi_data.maskInfoList[i].id) > -1)) {
					delete(pi_data.maskInfoList[i].price);
				}
			}
			
			if (app.editor.cardBody && (cardsId.indexOf(app.editor.cardBody.maskInfo.id) > -1))
				app.editor.cardBody.maskInfo.price = 0;
		}
		
/*		
		protected function doLinkRelease(e: Event): void {
			app.linkDialog(pi_data.GETLINK, app.getLink());
		}
*/
		

		protected function doStartPayment(e: ObjectEvent): void {
		}

			
/*		protected function doStartPayment(e: ObjectEvent): void {
			app.externalserver.openPayDialog(e.object.sms_price, e.object.other_price, function(): void {
				app.alert(pi_data.PAYDIALOGTITLE, pi_data.PAYDESCRIPTION, function(): void {
					var timer: Timer = new Timer(10000, 1); // Таймер проверки баланса 10 раз по 15 сек.
					var checkCount: int = 0;
					
					function doNextCheckBalance(result: Boolean): void {
						if (!result) {
							checkCount++;
							if (checkCount == 10) app.dispatchEvent(new Event(pi_events.PAYBAD));
							else timer.start();
						} else if (e.object.postPay) e.object.postPay();
					}
					timer.addEventListener(TimerEvent.TIMER_COMPLETE, function(e: TimerEvent): void {
						checkChangeBalance(doNextCheckBalance);
					});
					
					checkChangeBalance(doNextCheckBalance);
				});
			})
			
		}*/
		
		protected function checkChangeBalance(_handle: Function): void { // Функция проверки изменения баланса
			app.myserver.getBalance(app.externalserver.user_id, function(data: *): void {
				if (data.response[0] && (data.response[0].balance != app.balance)) {
					app.dispatchEvent(new ObjectEvent(pi_events.CHANGEBALANCE, data.response[0].balance));
					_handle(true);
				} else _handle(false);
			});
		}
		
		protected function errorAlert(error: Object): void {
			app.alert(pi_data.WARNING, pi_data.sprintf(pi_data.ERROR_SERVER, error.error_code + ' (' + error.error_msg + ')'));
		}
		
		protected function doGDResponse(e: GDataEvent): void {
			if (e.data.error_code) errorAlert(e.data);
		} 
		
		protected function doCardSelect(e: ObjectEvent): void {
			if (app.fullScreen) app.fullScreen.unloadAll();
			
//			_photoFromCard = new CLoader(app, e.object.params.photo,  function(pe: Event): void { 
				app.viewCard(e.object.params);
				if (!e.object.received && (e.object.sendTo == app.externalserver.viewer_id)) 
					app.myserver.receiveCardViewedAsUser(app.externalserver.viewer_id, e.object.send_id, function(data: Object): void {
						e.object.received = parseInt(data.response[0].result1);
						app.userData.myData.receiveCount = parseInt(app.userData.myData.receiveCount) + parseInt(data.response[0].result2);
					});
/*			});
			_photoFromCard.visible = false;
			_photoFromCard.load(new URLRequest(e.object.params.photo));
			_photoFromCard.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e: Event): void {
				app.removeChild(_photoFromCard);
			});*/
		}
		
		protected function doInBox(e: Event): void {
			app.showInBox();
		};
		
		protected function doOutBox(e: Event): void {
			app.showOutBox();
		};
		
		protected function doPayService(serviceID: int, price: Number, // Номер сервиса, цена сервиса
										warningPrePay: String,	// Сообщение в диалоге о снятии со счета
										concentProc: Function,	// Функция вызывается когда оплата произведена
										posPayFunc: Function = null, // Функция вызывается после пополения счета
										params: String = '',
										smallBalanceDesc: String = '' // Строка добавляемая в начало сообщения об недостаточном балансе
										): void  {
			if (price) {
				if (price <= app.balance) { // Если текущий баланс достаточен для приобретения
					app.alert(pi_data.WARNING, warningPrePay, function(): void {
						app.transaction(-price, function(): void {
							concentProc();
						}, serviceID, params);
					}, true);
				} else { // Если на счету не достаточно средств, выводим сообщение, потом диалог пополения баланса
					app.alert(pi_data.WARNING, smallBalanceDesc + pi_data.sprintf(app.siteData.SMALLBALANCE, [price, app.balance]), function (): void {
						app.payDialog(posPayFunc);
					}, true);
				}
			}
		}
		
		public function doPayTimeAccess(message: String, price: Number, retFunc: Function=null): void {
			doPayService(
				pi_data.TA_ORDERTIMELIMIT_SERVICE,
				price,
				message,
				(retFunc == null)?doCollectorResultImage:retFunc,	// Если сняли со счета тогда получаем ссылку
				function(): void {
					doPayTimeAccess(message, price);	// Если пополнили баланс, тогда снова попытка снять с баланса за лимит времени
				}, '',
				message + '\n'
			);
		}
		
		protected function doPayCard(e: GDataEvent): void {
			PayCard(e.data as int);
		}
		
		protected function PayCard(a_cardID: int, endFunc: Function = null): void {
			doPayService(
				pi_data.TA_ORDER_START + a_cardID,
				app.editor.cardBody.maskInfo.price,
				pi_data.sprintf(app.siteData.PAYCARDDESC, app.editor.cardBody.maskInfo.price),
				function(): void { // Если сняли со счета, тогда сбрасываем для этого шаблона цену
					if (a_cardID == app.editor.cardBody.maskInfo.id)
						app.editor.cardBody.maskInfo.price = 0;
					app.dispatchEvent(new ObjectEvent(pi_events.CLEARPRICE, [a_cardID]));
					if (endFunc != null) endFunc();
				},
				function(): void {
					PayCard(a_cardID, endFunc);
				}
			);
		}
		
		public function checkCollectPrepaid(params: Object, 
											collectFunc: Function, 
											paramFunc: Object = null, 
											retFunc: Function = null,
											myServerFunc: String = 'collectorImage'): void {
			function lastCollectResult(data: *): void {
				if (data.response && data.response[0]) {
					if (data.response[0].timeNoAccess) { // Если нет проплаченной услуги безлимита
						if (data.response[0].timeNoAccess == -1) { // Если вышел лимит бесплатных сохранений
							doPayTimeAccess(data.response[0].timeNoDescr, parseFloat(data.response[0].price), retFunc); // Пытаемся снять с баланса, если он не нулевой
						} else { // Если еще есть бесплатные сохранения
							var alert: pi_alertBaseTime = new app.classes.alertTime(app.layers[4], data.response[0].timeNoDescr,
														parseInt(data.response[0].timeNoAccess), function(): void { // Выдаем сообщение что возможно только через какоето время
								doPayTimeAccess(data.response[0].timeNoUnset, parseFloat(data.response[0].price), retFunc); // Если выбарна услуга безлимита, пытаемся снять с баланса
							}, function(): void {
								alert.close();
								_lastCollectFileTime = parseInt(data.response[0].time);
								collectFunc(paramFunc?paramFunc:data.response[0].file);								
							});
							alert.title.text = pi_data.WARNING;
							alert.show();
						}
					} else { // Если есть услуга безлимита, или можно сохранять бесплатно пришел файл
						_lastCollectFileTime = parseInt(data.response[0].time);
						collectFunc(paramFunc?paramFunc:data.response[0].file);
					}
				}
			}
			
			var a_params: Array = [
				{pn:'querycount', pv: 1}
			];
			
			var request: URLRequest = null;
			
			if (!(params is String) && (params.JPGData is ByteArray)) {
				a_params.push({pn:'query1', pv: pi_myserver.MODEL_NAME + ';uploadJPGCard;' + app.externalserver.viewer_id + ';' + params.path + ';' + (params.uploadURL?params.uploadURL:'')});
				
				var header:	URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
				request = app.myserver.createRequest(a_params, pi_servers.UPLOADJPG_URL, URLRequestMethod.GET);
				request.method = URLRequestMethod.POST;
				request.requestHeaders.push(header);
				request.data 	= params.JPGData;
			} else {
				a_params.push({pn:'query1', pv: pi_myserver.MODEL_NAME + ';' + myServerFunc + ';' + app.externalserver.viewer_id + ';' + params + ';' + _lastCollectFileTime});
			}
			
			app.myserver[myServerFunc](a_params, lastCollectResult, request);
			
//			app.myserver.jsrHelper(a_params, lastCollectResult, myServerFunc, false, '', request);
//			app.myserver['myServerFunc'](app.externalserver.user_id, params, _lastCollectFileTime, lastCollectResult);
		}
		
		public function collectJPG(jpg_data: ByteArray, collectFunc: Function, collectPath: String='from_albums', 
									incSaved: Boolean = true, checkPaid: Boolean = true): void {

			function collectBitmap(p: Object=null): void {
				checkCollectPrepaid({JPGData: jpg_data, path: collectPath}, function(fileName: String): void {
					collectFunc(fileName);
					if (incSaved && !app.userData.isPaidLimit) app.saveNotify();
				});
			}
			
			function toFileSave(e: Object=null): void {
				checkCollectPrepaid('', collectBitmap, e, toFileSave, 'checkPrepaid');
			}
			
			if (app.userData.isPaidLimit || !checkPaid) collectBitmap();
			else toFileSave();
		}
		
		public function saveJPG(JPGData: ByteArray, fileName: String='', 
								incSaved: Boolean = true, checkPaid: Boolean = true): void {
									
			function saveToFile(e: Object=null): void {
				
				var alert: pi_alert = new pi_alert(app.layers[5], pi_data.SAVEDESCR, null, true);
				alert.title.text = pi_data.WARNING;
				alert.okButton.addEvent(MouseEvent.CLICK, function(e: Event): void {				
					var fr: FileReference;
					fr = new FileReference();
					if (incSaved) {
						function l_doComplete(e: Event): void {
							fr.removeEventListener(Event.COMPLETE, l_doComplete);
							if (incSaved) app.saveNotify();
						}
						fr.addEventListener(Event.COMPLETE, l_doComplete);
					}
					fr.save(JPGData, fileName?fileName:app.genFileNameCard());
				});
				alert.show();
			}
			
			function repeatCall(e: Object=null): void {
				saveJPG(JPGData, fileName, incSaved, checkPaid);
			}
			
			if (checkPaid && !app.userData.isPaidLimit) 
				checkCollectPrepaid('', saveToFile, null, repeatCall, 'checkPrepaid');
			else saveToFile();
		}
		
		protected function doCollectorResultImage(e: Event=null): void {
			var card: pi_cardbody = app.isFullView?app.fullScreen:app.cardbody; // Если на полный экран то берем от туда
			if (card.card_photo.contentLoaderInfo.bytesLoaded > 0) {
				var params: String;
				params = card.infoFromCollector();
				if (card is pi_pngcard) {
					if (card.bmpContent()) {
						params += '&cardClass=pi_pngcard';
// 						Созранение PHG карт реализованно в классе pi_toolbar
					} else params += '&cardClass=pi_pngcardswf';
				} else params += '&cardClass=pi_pjc';
				if (e is ObjectEvent) params += '&' + (e as ObjectEvent).object;
				
				checkCollectPrepaid(params, function(fileName: String): void {
					app.download(fileName);
				});
			} else app.alert(pi_data.WARNING, pi_data.SELECTPHOTOTEXT);
		}
		
/*		public function checkPaidEffects(postFunc: Function): Boolean {
			if ((app.cardbody is pi_pngcard) && 
				(pi_data.effects[pi_data.effectIndex((app.cardbody as pi_pngcard).effectID)].paid) && 
				(!_paidEffects)) {
				doPayService(pi_data.TA_EFFECTS, pi_data.EFFECTS_PRICE, pi_data.PAYEFFECTSDESC, function(): void {
					app.dispatchEvent(new Event(pi_events.PAIDEFFECTS));
					postFunc();
				}, postFunc, '', pi_data.PAYFROMEFFECTSDESC);
				return false;
			} else return true;
		}*/
		
		public function checkPaidCard(postFunc: Function): Boolean {
			if (app.cardbody.maskInfo.price) {
				PayCard(app.cardbody.maskInfo.id, postFunc);
				return false;
			} else return true;
		}
		
		protected function afterSend(users: Array, data: Object, textPublish: String, link: String): void {
		}
		
		protected function send(users: Array, count_request:int=0): void {
			
			if (count_request > 2)
				app.alert(pi_data.ERROR, pi_data.SERVERNOACCESS);
			else {
				var s_users: String = usersToString(users);
				
				app.cardbody.createFromSend(function(link: String): void {
					app.myserver.sendCard(app.externalserver.viewer_id, users, link, pi_app.userName(app.userData),
						(!app.userData.isOut)?1:0,
						function(data:*): void {
							var textPublish: String = pi_data.sprintf(pi_data.USERSENDCARDTEXT, s_users);
	
							if (data.response && (data.response.length > 0) && (!data.response[0].error)) 
								afterSend(users, data.response[0], textPublish, link);
//							else send(users, count_request + 1); 
					});
				})
			}
		}
		
		protected function usersToString(users: Array): String {
			var s_users: String = '';
			for each (var user:* in users) {
				s_users += (s_users?', ':'') + pi_app.userName(user);
			}
			return s_users;
		}
		
		public function requestSend(users: Array): void {
			if (users.length == 0) return;
			
			app.externalserver.getFriends(app.externalserver.user_id, function(data: Array): void {
				
				function checkInstall(item:*, index:int, array:Array): * {
					for each (var d_user:* in data)
						if (d_user.uid == item.uid) {
							item.install = true;
							break;
						}
					return item;
				}
				var result: Array = users.map(checkInstall);
				if (result.length > 0) {
					var noInstall: Boolean = false;
					for each (var user:* in result) {
						if (!user.install) {
							noInstall = true;
							break;
						}
					}
					if (noInstall) { 
						app.alert(pi_data.WARNING, 
							pi_data.USERSNOINSTALL,
							function(): void {
								send(result);
							});
					} else send(result);
				}
			}, 'app_users');
		}
		
	}
}